package com.ruoyi.system.service.impl;

import java.util.Arrays;
import java.util.List;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.SealJurVo;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.Base64Utils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.jm.GmUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.mapper.SealInfoMapper;
import com.ruoyi.system.mapper.SealTempjurMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Objects;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.mapper.SealJurMapper;

/**
 * 印章授权Service业务层处理
 *
 * @author ess
 * @date 2021-11-03
 */
@Service
public class SealJurServiceImpl implements ISealJurService {
    @Autowired
    private SealJurMapper sealJurMapper;

    @Autowired
    private ISealInfoService sealInfoService;

    @Autowired
    private SealInfoMapper sealInfoMapper;

    @Autowired
    private IBusinessSysService businessSysService;

    @Autowired
    private SealTempjurMapper sealTempjurMapper;

    @Autowired
    private IPersonService personService;

    @Autowired
    private ISysUserService userService;

    @Override
    public boolean checkSealJur(String userId, String businessSysIds, String sealId) {
        List<SealJur> sealJurs = selectAllSealJurByUserId(userId,businessSysIds);
        for (SealJur s1 : sealJurs) {
            if (sealId.equals(s1.getSealId())){
                return true;
            }
        }
        return false;
    }

    @Override
    public List<SealJur> selectAllSealJurByUserId(String userId,String businessSysIds) {
        SealJur sealJur = new SealJur();
        sealJur.setSealPersonId(userId);
        sealJur.setBusinessSysIds(businessSysIds);
        //根据条件查出授权列表
        List<SealJur> jurList = sealJurMapper.selectSealJurList(sealJur);
        //去除没有对应印章的无效授权
        for (SealJur s1:jurList) {
            SealInfo sealInfo = sealInfoService.selectSealInfoBySealInfoId(s1.getSealId());
            if (Objects.isNull(sealInfo)) {
                jurList.remove(s1);
            }
        }
        return jurList;
    }
    /**
     * 查询印章授权
     *
     * @param sealJurId 印章授权主键
     * @return 印章授权
     */
    @Override
    public SealJur selectSealJurBySealJurId(String sealJurId) {
        return sealJurMapper.selectSealJurBySealJurId(sealJurId);
    }

    /**
     * 查询印章授权列表
     *
     * @param sealJur 印章授权
     * @return 印章授权
     */
    @Override
    public List<SealJur> selectSealJurList(SealJur sealJur) {

        ArrayList<SealJur> sealJurArrayList = new ArrayList<>();

        //印章姓名
        if (StringUtils.isNotEmpty(sealJur.getSealName())) {
            List<SealInfo> sealInfos = sealInfoService.selectSealInfoBySealName(sealJur.getSealName());
            if (sealInfos != null && sealInfos.size() > 0) {
                for (SealInfo sealInfo : sealInfos) {
                    sealJur.setSealId(sealInfo.getSealInfoId());
                    List<SealJur> jurList = sealJurMapper.selectSealJurList(sealJur);
                    if (jurList != null && jurList.size() > 0) {
                        for (SealJur jur : jurList) {
                            sealJurArrayList.add(jur);
                        }
                    }

                }

            }

            return takeSealJurReData(sealJurArrayList);
        }

        return takeSealJurReData(sealJurMapper.selectSealJurList(sealJur));

    }

    /**
     * 新增印章授权
     *
     * @param sealJur 印章授权
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSealJur(SealJur sealJur) {
//批量授权  可用印章类型 [[SYS001,ESS099],[SYS001,ESS100],[SYS002,ESS101]]  需判断单位中印章类型对应的印章
        if (sealJur.getType()==3) {
//            基本赋值
            sealJur.setSealOrHw(1L);
            sealJur.setIsAlreadyTempJurSeal(0L);
            sealJur.setJurTime(DateUtils.getTime());
            sealJur.setState(0L);
            String jurPLUnitId = sealJur.getUnitId();
            Object[] businessSysAndSealTypeArrs = sealJur.getBusinessSysIdArrs();
            for (int i = 0; i < businessSysAndSealTypeArrs.length; i++) {
                List<String> result = new ArrayList<>();
                if (businessSysAndSealTypeArrs[i] instanceof ArrayList<?>) {
                    for (Object o : (List<?>) businessSysAndSealTypeArrs[i]) {
                        result.add(String.class.cast(o));
                    }
                }

                String busin=result.get(0);;
                sealJur.setBusinessSysIds(busin);
                String sealTypeId=result.get(1);
                //根据单位id和印章类型查找可用的印章进行授权
               List<String> sealIds= sealInfoService.selectSealIdsBySealTypeAndUnitId(sealTypeId,jurPLUnitId);
                if (sealIds != null && sealIds.size() > 0) {
                    for (String sealId : sealIds) {
//                        判断时候有授权  有的话修改  没有的话添加
                        SealJur sealJurBusinessQuery = new SealJur();
                        sealJurBusinessQuery.setBusinessSysIds(sealJur.getBusinessSysIds());
                        sealJurBusinessQuery.setSealPersonId(sealJur.getSealPersonId());
                        sealJurBusinessQuery.setSealId(sealId);
                        List<SealJur> sealJurBusinessQueryIsEx = sealJurMapper.selectSealJurList(sealJurBusinessQuery);
                        if (sealJurBusinessQueryIsEx != null && sealJurBusinessQueryIsEx.size() > 0) {
                            sealJur.setSealJurId(sealJurBusinessQueryIsEx.get(0).getSealJurId());
                            //        计算hash值
                            String sealJurHash = Base64Utils.ESSGetBase64Encode(GmUtil.sm3(sealJur.toString().getBytes()));
                            sealJur.setSafeHash(sealJurHash);
                            sealJurMapper.updateSealJur(sealJur);

                        }else{
                            //        授权id 、hash
                            sealJur.setSealId(sealId);
                            //        主键uuid
                            sealJur.setSealJurId(IdUtils.fastSimpleUUID());
                            //        计算hash值
                            String sealJurHash = Base64Utils.ESSGetBase64Encode(GmUtil.sm3(sealJur.toString().getBytes()));
                            sealJur.setSafeHash(sealJurHash);
                            sealJurMapper.insertSealJur(sealJur);
                        }
                    }
                }

            }

            return 1;
        }else {


//        手签授权时查找
            if (sealJur.getType() == 2) {
                String sealInfoId = sealInfoMapper.selectSealInfoIdBySealPersonId(sealJur.getSealPersonId());
                sealJur.setSealId(sealInfoId);
                sealJur.setSealOrHw(0L);
            } else {
//            印章单独授权
                sealJur.setSealOrHw(1L);
            }
            sealJur.setIsAlreadyTempJurSeal(0L);
            sealJur.setJurTime(DateUtils.getTime());
            sealJur.setState(0L);
            if (sealJur.getFileTypeNumArr() != null && sealJur.getFileTypeNumArr().length > 0) {
                String fileType = "";
                for (int i = 0; i < sealJur.getFileTypeNumArr().length; i++) {
                    fileType += (String) sealJur.getFileTypeNumArr()[i] + ",";
                }
                sealJur.setFileTypeNum(fileType.substring(0, fileType.length() - 1));
            }


//      判断是否有选择多个业务系统 如选择需要分开添加多条数据
//        if (sealJur.getBusinessSysIdArrs() != null&&sealJur.getBusinessSysIdArrs().length>0) {
            for (int i = 0; i < sealJur.getBusinessSysIdArrs().length; i++) {
//
////                    判断是否有此业务系统的授权   有的话修改   没有的话添加
                SealJur sealJurBusinessQuery = new SealJur();
                sealJurBusinessQuery.setBusinessSysIds((String) sealJur.getBusinessSysIdArrs()[i]);
                sealJurBusinessQuery.setSealPersonId(sealJur.getSealPersonId());
                sealJurBusinessQuery.setSealId(sealJur.getSealId());//***
                List<SealJur> sealJurBusinessQueryIsEx = sealJurMapper.selectSealJurList(sealJurBusinessQuery);

                if (sealJurBusinessQueryIsEx != null && sealJurBusinessQueryIsEx.size() > 0) {
                    sealJur.setBusinessSysIds((String) sealJur.getBusinessSysIdArrs()[i]);
                    sealJur.setSealJurId(sealJurBusinessQueryIsEx.get(0).getSealJurId());
                    //        计算hash值
                    String sealJurHash = Base64Utils.ESSGetBase64Encode(GmUtil.sm3(sealJur.toString().getBytes()));
                    sealJur.setSafeHash(sealJurHash);
                    sealJurMapper.updateSealJur(sealJur);

                } else {
                    sealJur.setBusinessSysIds((String) sealJur.getBusinessSysIdArrs()[i]);
                    //        主键uuid
                    sealJur.setSealJurId(IdUtils.fastSimpleUUID());
                    //        计算hash值
                    String sealJurHash = Base64Utils.ESSGetBase64Encode(GmUtil.sm3(sealJur.toString().getBytes()));
                    sealJur.setSafeHash(sealJurHash);
                    sealJurMapper.insertSealJur(sealJur);
                }


            }
//        } else {
//            //        主键uuid
//            sealJur.setSealJurId(IdUtils.fastSimpleUUID());
//            //                计算hash值
//            String sealJurHash = Base64Utils.ESSGetBase64Encode(GmUtil.sm3(sealJur.toString().getBytes()));
//            sealJur.setSafeHash(sealJurHash);
//            sealJurMapper.insertSealJur(sealJur);
//        }

        return 1;
        }
    }

    /**
     * 修改印章授权
     *
     * @param sealJur 印章授权
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSealJur(SealJur sealJur) {
        return sealJurMapper.updateSealJur(sealJur);
    }

    /**
     * 批量删除印章授权
     *
     * @param sealJurIds 需要删除的印章授权主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSealJurBySealJurIds(String[] sealJurIds) {
        sealJurMapper.deleteSealTempjurBySealJurIds(sealJurIds);
        return sealJurMapper.deleteSealJurBySealJurIds(sealJurIds);
    }

    /**
     * 删除印章授权信息
     *
     * @param sealJurId 印章授权主键
     * @return 结果
     */
    @Override
    public int deleteSealJurBySealJurId(String sealJurId) {
        sealJurMapper.deleteSealTempjurBySealJurId(sealJurId);
        return sealJurMapper.deleteSealJurBySealJurId(sealJurId);
    }

    /**
     * 先清空授权表为手签的数据 以及对应的转授数据
     */
    @Override
    public void deleteAllSignJurAndTempJurData() {
        sealTempjurMapper.deleteAllSignTempJur();
        sealJurMapper.deleteAllSignJur();
    }

    /**
     * 删除印章授权信息
     *
     * @param personId 使用人id
     */
    @Override
    public void deleteSealJurBySealPersonId(String personId) {
        sealJurMapper.deleteSealTempJurBySealPersonId(personId);
        sealJurMapper.deleteSealJurBySealPersonId(personId);
    }

    @Override
    public boolean checkAreadyJur(SealJur sealJur) {
        //批量印章授权不检查是否已授权
        if (sealJur.getType()==3){
            return false;
        }else {
            //        手签授权时查找
            if (sealJur.getType() == 2) {
                String sealInfoId = sealInfoMapper.selectSealInfoIdBySealPersonId(sealJur.getSealPersonId());
                sealJur.setSealId(sealInfoId);
            }

            SealJur sealJurCheck = new SealJur();
            sealJurCheck.setSealId(sealJur.getSealId());
            sealJurCheck.setSealPersonId(sealJur.getSealPersonId());
//        区分业务系统的判断
//        if (sealJur.getBusinessSysIdArrs() != null&&sealJur.getBusinessSysIdArrs().length>0) {
            int numSealJur = 0;
            for (int i = 0; i < sealJur.getBusinessSysIdArrs().length; i++) {

                sealJurCheck.setBusinessSysIds((String) sealJur.getBusinessSysIdArrs()[i]);
                List<SealJur> sealJurs = sealJurMapper.selectSealJurList(sealJurCheck);
                if (sealJurs != null && sealJurs.size() > 0 && Arrays.toString(sealJur.getBusinessSysIdArrs()).contains(sealJurs.get(0).getBusinessSysIds())) {
                    numSealJur += 1;
                }
            }

            if (numSealJur == sealJur.getBusinessSysIdArrs().length) {
                return true;
            } else {
                return false;
            }

//        } else {
//            List<SealJur> sealJurs = sealJurMapper.selectSealJurList(sealJurCheck);
//            if (sealJurs != null && sealJurs.size() > 0) {
//                return true;
//            } else {
//                return false;
//            }
//        }
        }


    }

    /**
     * 新增印章转授管理信息
     *
     * @param sealJur 印章授权对象
     */
    public void insertSealTempjur(SealJur sealJur) {
        List<SealTempjur> sealTempjurList = sealJur.getSealTempjurList();
        String sealJurId = sealJur.getSealJurId();
        if (StringUtils.isNotNull(sealTempjurList)) {
            List<SealTempjur> list = new ArrayList<SealTempjur>();
            for (SealTempjur sealTempjur : sealTempjurList) {
                sealTempjur.setSealJurId(sealJurId);
                list.add(sealTempjur);
            }
            if (list.size() > 0) {
                sealJurMapper.batchSealTempjur(list);
            }
        }
    }


    private List<SealJur> takeSealJurReData(List<SealJur> sealJurs) {
        if (sealJurs != null && sealJurs.size() > 0) {
            for (SealJur jur : sealJurs) {
                SealJurVo sealJurVo = new SealJurVo();
//                印章名称
                if (StringUtils.isNotEmpty(jur.getSealId())) {
                    SealInfo sealInfo = sealInfoService.selectSealInfoBySealInfoId(jur.getSealId());
                    if (sealInfo != null) {
                        sealJurVo.setSealName(sealInfo.getSealName());
                    } else {
                        sealJurVo.setSealName(Constants.ERR_NAME);
                    }
                }

                if (StringUtils.isEmpty(jur.getIp())) {
                    sealJurVo.setIpName(Constants.NOT_IMPOSE);
                }
                if (StringUtils.isEmpty(jur.getMac())) {
                    sealJurVo.setMacName(Constants.NOT_IMPOSE);
                }
                if (StringUtils.isEmpty(jur.getFileTypeNum())) {
                    sealJurVo.setFileTypeName(Constants.NOT_IMPOSE);
                }
                if (jur.getUseCount() == null || jur.getUseCount() == -1) {
                    sealJurVo.setUseContName(Constants.NOT_IMPOSE);
                }
//                业务系统名称 如有多个
                if (StringUtils.isNotEmpty(jur.getBusinessSysIds())) {
                    String businessSysNames = "";
                    String[] splitBusinessSys = jur.getBusinessSysIds().split(",");
                    for (String splitBusinessSy : splitBusinessSys) {
                        BusinessSys businessSys = businessSysService.selectBusinessSysByBSysId(splitBusinessSy);
                        businessSysNames += businessSys.getbName() + ",";
                    }
                    sealJurVo.setBusinessSysNames(businessSysNames.substring(0, businessSysNames.length() - 1));
                } else {
                    sealJurVo.setBusinessSysNames(Constants.NOT_IMPOSE);
                }

//                使用人姓名
                Person person = personService.selectPersonByPersonId(jur.getSealPersonId());
                if (person != null) {
                    sealJurVo.setJurUseUserName(person.getPersonName() + "-" + person.getBirNum().substring(4));
                } else {
                    sealJurVo.setJurUseUserName(Constants.ERR_NAME);
                }
//                转授人姓名
                SysUser sysUser = userService.selectUserById(Long.valueOf(jur.getJurUserId()));
                if (sysUser != null) {
                    sealJurVo.setJurUserName(sysUser.getUserName());
                } else {
                    sealJurVo.setJurUserName(Constants.ERR_NAME);
                }

                jur.setSealJurVo(sealJurVo);
            }
        }

        return sealJurs;

    }
}
